<template>
  <div>
    <search-cirteria />
    <div class="table-container">
      <table-operate>
        <n-button
          size="small"
          type="primary"
          @click="handleShowModal"
        >
          <template #icon>
            <n-icon :component="AddSharp" />
          </template>
          新增
        </n-button>
      </table-operate>
      <data-table
        :columns="columns"
        :data="list"
        :loading="loading"
      />
      <pagination
        :total="total"
        v-model:page-num="pageNum"
        v-model:page-size="pageSize"
        @update:pageNum="query"
        @update:pageSize="query"
      />
      <modal-form
        title="用户管理"
        v-model:show="visible"
        :config="modalConfig"
        @confirm="handleConfirm"
        v-model:form="form"
        @cancel="handleCancel"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { h } from 'vue'
  import { NButton, useDialog, NFlex } from 'naive-ui'
  import type { DataTableColumns } from 'naive-ui'
  import type { ModalFormConfig } from '@/components/ModalForm/index.vue'
  import type { User } from '@/api/power/user'
  import { AddSharp } from '@vicons/ionicons5'
  import SearchCirteria from '@/components/SearchCriteria/index.vue'
  import Pagination from '@/components/Pagination/index.vue'
  import TableOperate from '@/components/TableOperate/index.vue'
  import TableButton from '@/components/TableButton/index.vue'
  import ModalForm from '@/components/ModalForm/index.vue'
  import DictTag from '@/components/DictTag/index.vue'

  import { addUser, updateUser, getUserList, deleteUser, getUser } from '@/api/power/user'
  import { getAllRole } from '@/api/power/role'
  import { useCurd } from '@/hooks/useCrud'
  import { useDict } from '@/hooks/useDict'
  import { useMessage } from 'naive-ui'

  import dayjs from 'dayjs'

  const { sys_common_status } = useDict('sys_common_status')

  const message = useMessage()
  const dialog = useDialog()
  // 窗口显示/隐藏
  const visible = ref(false)
  // 表单数据
  const form = ref<User>({
    username: '',
    status: '1',
    roleIds: []
  })

  // 显示新增窗口
  const handleShowModal = (id: any) => {
    if (typeof id === 'number') {
      getUser(id).then(res => {
        form.value = res.data
      })
    }
    visible.value = true
  }

  function handleDelete(id: number) {
    dialog.warning({
      title: '提示',
      content: '是否确定删除数据？',
      positiveText: '确认',
      negativeText: '取消',
      onPositiveClick: async () => {
        await deleteUser(id)
        message.success('删除成功')
        query
      }
    })
  }

  // 确认保存
  const handleConfirm = async () => {
    if (form.value.userId) {
      const { userId, ...arg } = form.value
      await updateUser(userId, arg)
      message.success('修改用户成功')
    } else {
      await addUser(form.value)
      message.success('新增用户成功')
    }
    handleCancel()
    query()
  }

  // 取消保存
  const handleCancel = () => {
    form.value = {
      username: '',
      status: '1',
      roleIds: []
    }
    visible.value = false
  }

  const getAllSelectRole = async () => {
    const res = await getAllRole()
    const lastIndex = modalConfig.value.length - 1
    if (modalConfig.value[lastIndex].type === 'multiple-select') {
      modalConfig.value[lastIndex].options = res.data.map(role => ({
        label: role.roleName,
        value: role.roleId
      }))
    }
  }

  onMounted(() => {
    getAllSelectRole()
  })

  const { query, list, queryParams, total, pageNum, pageSize, loading } = useCurd({
    queryFn: getUserList
  })

  const createColumns = (): DataTableColumns<any> => {
    return [
      {
        title: '用户名',
        key: 'username'
      },
      {
        title: '手机号',
        key: 'phoneNumber'
      },
      {
        title: '状态',
        key: 'stauts',
        render: row => h(DictTag, { options: sys_common_status.value, value: row.status })
      },
      {
        title: '排序',
        key: 'sort'
      },
      {
        title: '创建时间',
        key: 'createTime',
        render: row => dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
      },
      {
        title: '操作',
        key: 'actions',
        width: 300,
        render(row) {
          return h(
            NFlex,
            { justify: 'center' },
            {
              default: () => [
                h(
                  TableButton,
                  {
                    type: 'primary',
                    onClick: () => handleShowModal(row.userId)
                  },
                  {
                    default: () => '修改'
                  }
                ),
                h(
                  TableButton,
                  {
                    type: 'error',
                    onClick: () => handleDelete(row.userId)
                  },
                  {
                    default: () => '删除'
                  }
                )
              ]
            }
          )
        }
      }
    ]
  }

  const columns = createColumns()

  const modalConfig = ref<ModalFormConfig[]>([
    {
      type: 'input-number',
      label: '手机号',
      key: 'phoneNumber',
      show: true
    },
    {
      type: 'input-number',
      label: '排序',
      key: 'sort',
      show: true
    },
    {
      type: 'input',
      label: '昵称',
      key: 'nickName',
      show: true
    },
    {
      type: 'radio',
      label: '状态',
      key: 'status',
      show: true,
      options: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
      ]
    },
    {
      type: 'multiple-select',
      label: '角色',
      key: 'roleIds',
      show: true,
      span: 24,
      options: []
    }
  ])
</script>

<style scoped lang="scss"></style>
